package com.a01_2021.thousandstimes.general.controller;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.exception.CustomExceptionType;
import com.a01_2021.thousandstimes.general.entity.SysMenu;
import com.a01_2021.thousandstimes.general.service.SysMenuService;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author E1xP@foxmail.com
 * @version 1.0
 * @PACKAGE_NAME com.a01_2021.thousandstimes.auth.controller
 * @CLASS_NAME SysMenuController
 * @Description TODO 权限相关控制器
 * @Date 2021/3/3 上午 10:50
 **/
@RestController
@RequestMapping("/sys-menu")
public class SysMenuController {

    @Resource
    SysMenuService sysMenuService;

    /**
     * 添加权限
     *
     * @param menuName 权限名
     * @param url      权限url
     * @return AjaxResponse
     * @throws CustomException 当权限已存在时抛出异常
     */
    @PreAuthorize("hasAuthority('sys-menu-addMenu')")
    @DS("#header.instanceid")
    @PostMapping("addMenu")
    public AjaxResponse addMenu(String menuName, String url) throws CustomException {
        if (StringUtils.isEmpty(menuName)) {
            //若权限名为空
            return AjaxResponse.error(CustomExceptionType.USER_INPUT_ERROR, "权限名输入不得为空");
        }
        SysMenu sysMenu = sysMenuService.addMenu(menuName, url);
        return AjaxResponse.success(sysMenu);
    }

    /**
     * 删除权限
     *
     * @param menuId 权限id
     * @return AjaxResponse
     * @throws CustomException 当权限不存在，权限未闲置时抛出异常
     */
    @PreAuthorize("hasAuthority('sys-menu-addMenu')")
    @DS("#header.instanceid")
    @PostMapping("removeMenu")
    public AjaxResponse removeMenu(long menuId) throws CustomException {
        sysMenuService.removeMenu(menuId);
        return AjaxResponse.success("成功删除权限");
    }

}
